package com.rtsapp.server.benchmark.runner.channel;

/**
 * Created by admin on 16-6-18.
 */

import com.rtsapp.server.benchmark.cases.cmd.CommandCaseHandler;
import com.rtsapp.server.common.ByteBuffer;
import com.rtsapp.server.common.IByteBuffer;
import com.rtsapp.server.logger.Logger;
import com.rtsapp.server.logger.LoggerFactory;
import com.rtsapp.server.network.protocol.command.ICommand;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 输出服务器编码
 */
public class CommandTestOutHandler  extends MessageToByteEncoder<ICommand> {

    private static final Logger LOG = LoggerFactory.getLogger(CommandTestOutHandler.class);

    private final CommandCaseHandler commandCaseHandler;

    public CommandTestOutHandler(  CommandCaseHandler commandCaseHandler ){
        this.commandCaseHandler = commandCaseHandler;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, ICommand command, ByteBuf out)
            throws Exception {


        try {
            int startIdx = out.writerIndex();
            IByteBuffer buffer = new ByteBuffer(out);

            buffer.writeInt(0);

            commandCaseHandler.sendPackageHead(buffer);

            command.writeToBuffer(buffer);
            int endIdx = out.writerIndex();
            out.setInt(startIdx, endIdx - startIdx - 4);
        }catch( Throwable ex ){
            LOG.error( "消息输出编码出错:" , ex );
        }
    }

}